<script lang="ts" setup>
import { postPatientConsultOrderAPI, postPatientConsultPayAPI, preOrderAPI } from '@/apis/consult';
import { getPatientInfoAPI } from '@/apis/patient';
import { useUserConsultStore } from '@/stores/consult';
import type { OrderPreData } from '@/types/consult';
import type { EditPatientParams, PatientListData } from '@/types/patient';
import { ref } from 'vue';

const store = useUserConsultStore()
// 获取预下单信息
const preOrderInfo = ref<OrderPreData>()
const preOrder = async () => {
  const res = await preOrderAPI({
    type:store.type,
    illnessType:store.illnessType
  })
  preOrderInfo.value = res.data
} 
preOrder()
// 获取患者信息
const patientInfo = ref<Partial<PatientListData>>()
const getPatientInfo = async ()=>{
  const res = await getPatientInfoAPI(store.patientId)
  // console.log(res);
  patientInfo.value = res.data
}
getPatientInfo()
// 创建订单
// 保存订单id
const orderId = ref('')
const paymentRef = ref<UniHelper.UniPopupInstance>()
const handleCreateOrder = async () => {
    // 如果订单ID存在，则不能重复创建
    if (orderId.value !== '') {
      return uni.showToast({ title: '订单不能重复创建！', icon: 'error' })
    }
    // 创建订单
    const res = await postPatientConsultOrderAPI({
      type: Number(store.type),
      illnessType: Number(store.illnessType),
      patientId: store.patientId,
      depId: store.depId,
      illnessDesc: store.illnessInfo.illnessDesc,
      illnessTime: store.illnessInfo.illnessTime,
      consultFlag: store.illnessInfo.consultFlag,
      pictures: store.illnessInfo.pictures,
    })
    // console.log(res);
    
    // 接收订单ID
    orderId.value = res.data.id
    // 将 Pinia 中缓存的数据清空掉（订单已创建完成）
    // store.clear()
    // 打开弹窗
    paymentRef.value?.open?.()
  }
  /** 关闭支付弹窗 */
const handleClose = async () => {
  // 二次确认提示
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  // 如果用户选择关闭，则关闭支付弹窗
  if (res.cancel) {
    paymentRef.value?.close?.()
  }
}
// 确认支付
const handleConfirm = async (index: number) => {
  if (index === 0) {
    uni.showToast({ title: '暂不支持微信支付', icon: 'none' })
    // #ifdef MP-WEIXIN
    // 微信支付本质还是给后端发送请求，获取后端返回的微信支付所需要的参数
    // 然后调用微信支付接口，让微信进行支付
    // 支付成功后， we.requestPayment(后端返回的支付参数)
    // #endif
  }else if (index === 1) {
    
    const res = await postPatientConsultPayAPI({
      orderId: orderId.value,
      paymentMethod: index.toString(),
      // 支付完成，由支付宝打开问诊室页面，所以页面路径要完整，从 http 开始
      payCallback: 'http://localhost:5173/#/subpkg_consult/pages/room/room',
    })
    // console.log(res);
    // 把地址栏的 url 重定向到支付宝支付付款页面
    location.href = res.data.payUrl
    
  }
}

// 切换支付方式
const handleChange = (index: number) => {
  // console.log('切换支付方式', index)
}

</script>

<template>
  <scroll-page>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${preOrderInfo?.payment ?? ''}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item title="优惠券" show-arrow :right-text="`-¥${preOrderInfo?.couponDeduction ?? ''}`" />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{preOrderInfo?.pointDeduction ?? ''}}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{preOrderInfo?.payment ?? ''}}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        title="患者资料"
      >
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray" v-if="patientInfo"> {{patientInfo?.name }} | {{patientInfo?.genderValue }} | {{patientInfo?.age }} </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc ?? ''" />
        </uni-list>
      </uni-section>

      <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view>
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{preOrderInfo?.payment}}</text>
      </view>
      <button class="uni-button" @click="handleCreateOrder">立即支付</button>
      <custom-payment 
      ref="paymentRef"
      :orderId="orderId"
      v-if="preOrderInfo?.payment"
      :amount="preOrderInfo?.payment"
      @close="handleClose"
      @confirm="handleConfirm"
      @change="handleChange"
      ></custom-payment>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './index.scss';
</style>